package com.gzy.android_douban.ui.login;

import android.app.Activity;
import android.util.Log;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.appcompat.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.gzy.android_douban.R;
import com.gzy.android_douban.ui.login.LoginViewModel;
import com.gzy.android_douban.ui.login.LoginViewModelFactory;
import com.gzy.android_douban.databinding.ActivityLoginBinding;

public class LoginActivity extends AppCompatActivity {

  private LoginViewModel loginViewModel;
  private ActivityLoginBinding binding;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    binding = ActivityLoginBinding.inflate(getLayoutInflater());
    setContentView(binding.getRoot());

    loginViewModel = new ViewModelProvider(this, new LoginViewModelFactory())
        .get(LoginViewModel.class);

    // final EditText usernameEditText = binding.username;
    // final EditText passwordEditText = binding.password;
    // final Button loginButton = binding.login;
    // final ProgressBar loadingProgressBar = binding.loading;

    loginViewModel.getLoginFormState().observe(this, new Observer<LoginFormState>() {
      @Override
      public void onChanged(@Nullable LoginFormState loginFormState) {
        if (loginFormState == null) {
          return;
        }
        binding.login.setEnabled(loginFormState.isDataValid());
        if (loginFormState.getUsernameError() != null) {
          binding.username.setError(getString(loginFormState.getUsernameError()));
        }
        if (loginFormState.getPasswordError() != null) {
          binding.password.setError(getString(loginFormState.getPasswordError()));
        }
      }
    });

    loginViewModel.getLoginResult().observe(this, new Observer<LoginResult>() {
      @Override
      public void onChanged(@Nullable LoginResult loginResult) {
        if (loginResult == null) {
          return;
        }
        binding.loading.setVisibility(View.GONE);
        if (loginResult.getError() != null) {
          showLoginFailed(loginResult.getError());
        }
        if (loginResult.getSuccess() != null) {
          updateUiWithUser(loginResult.getSuccess());
        }
        setResult(Activity.RESULT_OK);

        //Complete and destroy login activity once successful
        finish();
      }
    });

    TextWatcher afterTextChangedListener = new TextWatcher() {
      @Override
      public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        Log.i("官场这", "2|" + "s:" + s + "|start:" + start + "|count:" + count + "|after:" + after);
        // ignore
      }

      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) {
        Log.i("官场这", "onTextChanged|" + "s:" + s + "|start:" + start + "|before:" + before + "|count:" + count);
        // ignore
      }

      @Override
      public void afterTextChanged(Editable s) {
        Log.i("官场这", "afterTextChanged|" + "s:" + s);
        loginViewModel.loginDataChanged(binding.username.getText().toString(),
            binding.password.getText().toString());
      }
    };

    binding.username.addTextChangedListener(afterTextChangedListener);
    binding.password.addTextChangedListener(afterTextChangedListener);

    binding.password.setOnEditorActionListener(new TextView.OnEditorActionListener() {

      @Override
      public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_DONE) {
          loginViewModel.login(binding.username.getText().toString(),
              binding.password.getText().toString());
        }
        return false;
      }
    });

    binding.login.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        binding.loading.setVisibility(View.VISIBLE);
        loginViewModel.login(binding.username.getText().toString(),
            binding.password.getText().toString());
      }
    });
  }

  private void updateUiWithUser(LoggedInUserView model) {
    String welcome = getString(R.string.welcome) + model.getLoggedInUser().getUserId();
    // TODO : initiate successful logged in experience
    Toast.makeText(getApplicationContext(), welcome, Toast.LENGTH_LONG).show();
  }

  private void showLoginFailed(@StringRes Integer errorString) {
    Toast.makeText(getApplicationContext(), errorString, Toast.LENGTH_SHORT).show();
  }
}